package com.mysoft.gfyx.clue.service.impl;

import com.mysoft.framework.context.api.ContextManager;
import com.mysoft.framework.sdk.system.api.MessagePush;
import com.mysoft.framework.sdk.system.api.SystemDataProvider;
import com.mysoft.framework.sdk.system.dto.UserDTO;
import com.mysoft.framework.service.AppService;
import com.mysoft.gfyx.clue.mip.OpptySubsSearchService;
import com.mysoft.gfyx.clue.mip.dto.OpptySubsSearchRequestDto;
import com.mysoft.gfyx.clue.service.OpptySubsCustomerDataService;
import com.mysoft.gfyx.clue.service.OpptySubsPurchaseDataService;
import com.mysoft.gfyx.clue.service.OpptySubsService;
import com.mysoft.gfyx.clue.service.OpptysubsTimingJobService;
import com.mysoft.gfyx.clue.service.dto.*;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjusters;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.UUID;

@Service

public class OpptysubsTimingJobServiceImp extends AppService implements OpptysubsTimingJobService {
    @Resource
    private OpptySubsSearchService opptySubsSearchService;

    @Resource
    private OpptySubsService opptysubsService;

    @Resource
    private OpptySubsCustomerDataService opptySubsCustomerDataService;

    @Resource
    private OpptySubsPurchaseDataService opptySubsPurchaseDataService;

    @Resource
    private MessagePush messagePush;

    @Resource
    private SystemDataProvider systemDataProvider;

    @Resource
    private ContextManager contextManager;


    @Override
    //商机查询
    public void opptySubsSearchTimingJobHandlerExec() throws Exception {
        //1.查询商机订阅配置
        List<OpptySubsDto> allEnabledOpptySubs = opptysubsService.getAllEnabledOpptySubs();
        System.out.println("allEnabledOpptySubs="+ allEnabledOpptySubs);
        //2.查询商机订阅配置过滤条件
        //todo
        //3.查询数据服务，获取商机列表
        for (int i = 0; i < allEnabledOpptySubs.size(); i++) {

            OpptySubsSearchRequestDto opptySubsSearchRequestDto = new OpptySubsSearchRequestDto();
            opptySubsSearchRequestDto.setKeyword("test");
            System.out.println("opptySubsSearchRequestDto====="+opptySubsSearchRequestDto);
            //查询结果
            LinkedHashMap searchResult = opptySubsSearchService.opptySubsSearch(opptySubsSearchRequestDto);
            //map转换成对象 todo
            //4.入库
            //todo
            int subsType = allEnabledOpptySubs.get(i).getSubsType();
            if (subsType == 0) {
                OpptySubsCustomerDataDto opptySubsCustomerDataDto = new OpptySubsCustomerDataDto();
                opptySubsCustomerDataDto.setCustomerName("name"+i);
                opptySubsCustomerDataDto.setCreditCode("code"+i);
                opptySubsCustomerDataDto.setOpptySubsGUID(allEnabledOpptySubs.get(i).getOpptySubsGUID());
                UUID uuid = opptysubsService.saveOpptySubsCustomerData(opptySubsCustomerDataDto);
            } else if (subsType == 1) {
                OpptySubsPurchaseDataDto opptySubsPurchaseDataDto = new OpptySubsPurchaseDataDto();
                opptySubsPurchaseDataDto.setBiddingOrg("setBiddingOrg"+i);
                opptySubsPurchaseDataDto.setCreditCode("code"+i);
                opptySubsPurchaseDataDto.setOpptySubsGUID(allEnabledOpptySubs.get(i).getOpptySubsGUID());
                UUID uuid = opptysubsService.saveOpptySubsPurchaseData(opptySubsPurchaseDataDto);
            }
        }
        System.out.println("done..");
    }


    @Override
    //商机推送
    public void opptySubsPushTimingJobHandlerExec() {
        //计算推送时间
        flushNextPushTime(null);
        //1.查询商机订阅配置
        //查询这一分钟内推送的订阅
        List<OpptySubsDto> allInOneMinuteEnabledOpptySubs = opptysubsService.getAllInOneMinuteEnabledOpptySubs();
        System.out.println("allInOneMinuteEnabledOpptySubs="+ allInOneMinuteEnabledOpptySubs);
        //2.推送消息
        for (OpptySubsDto opptySubsDto : allInOneMinuteEnabledOpptySubs) {
            try {
                PushDataStatDto pushDataStatDto = new PushDataStatDto();
                if (opptySubsDto.getSubsType() == OpptySubsService.SUBS_TYPE_CUSTOMER) {
                    //3.查询本次推送条数统计
                    pushDataStatDto = opptySubsCustomerDataService.pushDataStat(opptySubsDto.getOpptySubsGUID());

                    //4.批量设置商机数据已推送
                    opptySubsCustomerDataService.updatePush(opptySubsDto.getOpptySubsGUID());
                } else if (opptySubsDto.getSubsType() == OpptySubsService.SUBS_TYPE_PURCHASE) {
                    //3.查询本次推送条数统计
                    pushDataStatDto = opptySubsPurchaseDataService.pushDataStat(opptySubsDto.getOpptySubsGUID());

                    //4.批量设置商机数据已推送
                    opptySubsCustomerDataService.updatePush(opptySubsDto.getOpptySubsGUID());
                }

                // 5.推送站内信
                // 确认客户和采购类型的文案
                sendTaskWake(opptySubsDto, pushDataStatDto);
                System.out.println("已推送站内信。。。。。。。。");
                //6.推送短信、微信 todo
                // ...
                // 刷新下次调度计算时间
                flushNextPushTime(opptySubsDto.getOpptySubsGUID());
            } catch (Exception e) {
                //todo 记录日志
                flushNextPushTime(opptySubsDto.getOpptySubsGUID());
                System.out.println("opptySubsPushTimingJobHandlerExec报错"+e.getMessage());
            }
        }
    }
    //计算推送时间
    public void flushNextPushTime(UUID opptySubsGUID) {
        List<OpptySubsDto> allEnabledOpptySubsList = opptysubsService.getAllEnabledAndNextPushTimeIsNullOpptySubs(opptySubsGUID);
        for (OpptySubsDto enabledOpptySubs : allEnabledOpptySubsList) {
            //计算下次推送时间
            Integer pushCycle = enabledOpptySubs.getPushCycle();
            String pushCycleHour = enabledOpptySubs.getPushCycleHour();
            String pushCycleMinute = enabledOpptySubs.getPushCycleMinute();
            Date nextPushDate = null;
            //每天
            if (pushCycle == 0) {
                LocalDate tomorrow = LocalDate.now().plusDays(1);
                LocalDateTime localDateTime = LocalDateTime.parse(tomorrow+"T"+pushCycleHour+":"+pushCycleMinute+":00");
                System.out.println("tomorrow localDateTime====" + localDateTime);
                nextPushDate = Date.from(localDateTime
                        .atZone(ZoneId.systemDefault())
                        .toInstant());
                System.out.println("tomorrow date====" + nextPushDate);
            } else if (pushCycle <= 7) {
                LocalDate localDate = LocalDate.now().with(TemporalAdjusters.next(DayOfWeek.of(pushCycle)));
                LocalDateTime localDateTime = LocalDateTime.parse(localDate+"T"+pushCycleHour+":"+pushCycleMinute+":00");
                nextPushDate = Date.from(localDateTime
                        .atZone(ZoneId.systemDefault())
                        .toInstant());
            }
            if (nextPushDate == null) {
                continue;
            }
            OpptySubsDto saveOpptySubs = new OpptySubsDto();
            saveOpptySubs.setNextPushTime(nextPushDate);
            saveOpptySubs.setOpptySubsGUID(enabledOpptySubs.getOpptySubsGUID());
            UUID uuid = opptysubsService.saveOpptySubs(saveOpptySubs);
            System.out.println("uuid====" + uuid);
//                DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
//                String nextPushTime = dateTimeFormatter.format(localDateTime);
        }

    }

    public void sendTaskWake(OpptySubsDto opptySubsDto, PushDataStatDto pushDataStatDto) {
        //通知消息推送
        //todo 跳转地址
        final String pageUrl = "/MyWorkflow/WF_ProcessHandle_Form_Transfer.aspx";
        String[] getPushUserListSplit = opptySubsDto.getPushUserList().split(",");
        for (String pushUserGuid : getPushUserListSplit) {
            UserDTO user = systemDataProvider.getUser(pushUserGuid);
            String userName = user != null ? user.getUserName() : "";
            // todo 新拿地企业x家 ，新项目开盘企业x
            final String wakeSubject = " 尊敬的【"+userName+"】，您订阅【" + opptySubsDto.getSubsName() + "】，新增符合企业"+pushDataStatDto.getTotal()+"家";
            final String wakeType = "工作流消息";
            final UUID businessGuid = UUID.randomUUID();
            final String businessType = "商机订阅通知";
            final String appCode = "4022";
            String r = messagePush.sendTaskWake(pageUrl, UUID.fromString(pushUserGuid), wakeSubject, wakeType, appCode, businessGuid, businessType);
            System.out.println("结果======" + r);
        }
    }
}
